﻿using System;
using System.Data;
using System.Data.SQLite;

namespace Common
{
    /// <summary>
    /// SQLight工具类
    /// </summary>
    public class SQLiteTool
    {
        private static SQLiteConnection sqlite_conn;

        /// <summary>
        /// 创建数据库
        /// </summary>
        public static void CreateConnection()
        {
            sqlite_conn = new SQLiteConnection("Data Source= database.db; Version = 3; New = True; Compress = True; ");
            try
            {
                sqlite_conn.Open();
            }
            catch (Exception ex)
            {
                sqlite_conn.Close();
                throw ex;
            }
        }

        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="createSql"> </param>
        public static void CreateTable(string createSql)
        {
            SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
            sqlite_cmd.CommandText = createSql;
            sqlite_cmd.ExecuteNonQuery();
        }

        /// <summary>
        /// 创建索引
        /// </summary>
        /// <param name="createSql"> </param>
        public static void CreateIndex(string createSql)
        {
            SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
            sqlite_cmd.CommandText = createSql;
            sqlite_cmd.ExecuteNonQuery();
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="insertSql"> </param>
        public static void InsertData(string insertSql)
        {
            SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
            sqlite_cmd.CommandText = insertSql;
            sqlite_cmd.ExecuteNonQuery();
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="querySql"> </param>
        /// <param name="dt">       </param>
        public static void QrueyData(string querySql, out DataTable dt)
        {
            dt = new DataTable();
            SQLiteCommand sqlite_cmd = sqlite_conn.CreateCommand();
            sqlite_cmd.CommandText = querySql;

            SQLiteDataReader reader = sqlite_cmd.ExecuteReader();

            dt.Load(reader);
        }
    }
}